package netty.lora;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import netty.DataRequest;
import netty.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Author zhangtao
 * @create 2021/11/2 9:41
 */
public class LoraDecoder extends ByteToMessageDecoder {
    private static final Logger LOG = LoggerFactory.getLogger(LoraDecoder.class);
    private static final int MIN_HEAD_LENGTH = 9;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        DataRequest request = this.decode(byteBuf);
        System.out.println(request.toString());
        list.add(request);
    }

    public DataRequest decode(ByteBuf buf) {
        try {
            buf.markReaderIndex();
            byte[] head = new byte[MIN_HEAD_LENGTH];
            buf.readBytes(head);
            String header = ByteUtil.bytes2HexStr(head);
            String stationId = header.substring(0, 8);
            String loraId = header.substring(8, 16);
            String lengthStr = header.substring(16);
            LOG.info("stationId :{} id:{} len:{}", stationId, loraId, lengthStr);


            int length = ByteUtil.convertIntByLittle(ByteUtil.hextoBytes(lengthStr));
            byte[] content = new byte[length];
            buf.readBytes(content);
            String data = ByteUtil.bytes2HexStr(content);
            DataRequest request = new DataRequest(data, loraId, stationId);
            return request;
        } catch (Exception e) {
            return new DataRequest("", "005E793", "25963ffe");
        }
    }
}
